package main

import (
	"fmt"
	"net"
	"sync"
)

type Server struct {
	Ip        string `json:"ip"`
	Port      int    `json:"port"`
	OnlineMap map[string]*User
	mapLock   sync.Mutex
	Message   chan string
}

func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}
func (this *Server) Start() {
	// socket listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net.Listen error: ", err)
		return
	}
	// close listen socket
	defer listener.Close()

	// accept
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("net.Accept error: ", err)
			continue
		}
		go this.Handler(conn)
		go this.ListenMessage()
	}
	// do handler

}

// Handler
//
//	@Description: 当前链接的业务
//	@receiver this
//	@param conn
func (this *Server) Handler(conn net.Conn) {
	user := NewUser(conn, this)

	joinMessage := fmt.Sprintf("欢迎%s进入聊天室", user.Name)

	user.DoMessage(joinMessage)

	user.Online()

	go this.AcceptMessage(user, conn)
}
func (this *Server) AcceptMessage(user *User, conn net.Conn) {
	buf := make([]byte, 4096)
	for {
		n, err := conn.Read(buf)
		if n == 0 {
			user.Offline()
			return
		}
		if err != nil {
			fmt.Println("accept error: ", err)
			return
		}
		msg := string(buf[:n-1])
		user.DoMessage(msg)
	}
}

// Broadcast
//
//	@Description: 广播信息
//	@receiver this
func (this *Server) Broadcast(message string) {
	this.Message <- message
}
func (this *Server) ListenMessage() {
	for {
		message := <-this.Message
		this.mapLock.Lock()
		for _, user := range this.OnlineMap {
			user.C <- message
		}
		this.mapLock.Unlock()
	}
}
